import { login } from '@/api/login.js'
import { setSessionStorage, removeSessionStorage } from '@/utils/auth.js'
import router from '@/router'

const state = {
  info: {},
}

const mutations = {
  set_state: (state, data) => {
    for (const key in data) {
      state[key] = data[key]
    }
  },
  clear_state: (state) => {
    state = {
      info: {},
    }
  },
}

const actions = {
  async login({ commit }, data) {
    let user = await login(data)
    await commit('set_state', user)
    await commit('set_state', data)
    setSessionStorage('user', user)
  },

  setLogin({ commit }, data) {
    commit('set_state', data)
    setSessionStorage('user', data)
  },

  logOut({ commit }) {
    commit('clear_state')
    removeSessionStorage('user')
    router.push('/login')
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
